const _ = require('lodash');

/** @namespace app.model.Config */
module.exports = app => {
  const {STRING, JSON} = app.Sequelize;

  const Table = app.model.define('config', {
    key: {
      type: STRING,
      allowNull: false,
      comment: '键值对的key',
      primaryKey: true,
    },
    value: {
      type: JSON, comment: '键值对的value',
    },
  }, {
    timestamps: false,
    tableName: 'spider_config',
  });

  /** @function app.model.Config.getValue
   *  @param key {string}
   *  @param defaultValue {*}
   *  @return {*}
   */
  Table.get = async (key, defaultValue = null) => {
    const value = await Table.findOne({where: {key}});
    if (!value) {
      return defaultValue;
    }
    if (_.isNumber(value.value))
      return parseFloat(value.value);
    return value.value;
  };

  /** @function app.model.Config.setValue
   *  @param key {string}
   *  @param value {*}
   *  @return {Promise}
   */
  Table.set = (key, value) => {
    return Table.upsert({key, value});
  };

  return Table;
};